import axios from '@/plugins/axios/axios.js';
import cookies from '@/utils/cookies';

const tokenUrl = `/yjz-oauth/oauth/token?grant_type=client_credentials&scope=all&client_id=web&client_secret=yjz2016`;

export const getAuthToken = (token) => {
  return cookies.get('AuthorizationWeixin');
};

export const setAuthToken = (token) => {
  cookies.set(`AuthorizationWeixin`, token);
};

export const reloadAuthToken = (options) => {
  return axios(options).catch((data) => {
    return axios({
      method: 'GET',
      url: tokenUrl
    })
      .then((data) => {
        // 如果获取到 token
        if (data && data.access_token) {
          const saveTokenVal = `Bearer ${data.access_token}`;
          // 直接使用
          options.headers['Authorization'] = saveTokenVal;
          // 保存下来
          setAuthToken(saveTokenVal);
          return axios(options);
        }
        return {
          respCode: -100,
          respMsg: '认证失败'
        };
      })
      .catch(() => {
        return {
          respCode: -100,
          respMsg: '认证失败'
        };
      });
  });
};

export const initAuthToken = () => {
  return axios({
    method: 'GET',
    url: tokenUrl
  })
    .then((data) => {
      // 如果获取到 token
      if (data && data.access_token) {
        const saveTokenVal = `Bearer ${data.access_token}`;

        // 保存下来
        setAuthToken(saveTokenVal);
      }
      return {
        respCode: -100,
        respMsg: '认证失败'
      };
    })
    .catch(() => {
      return {
        respCode: -100,
        respMsg: '认证失败'
      };
    });
};
